<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>平台用户</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="5">
        <el-col :span="2"
          ><el-button
            class="button-size"
            type="warning"
            size="medium"
            @click="bpUser()"
            >禁用</el-button
          ></el-col
        >
        <el-col :span="2"
          ><el-button
            class="button-size"
            type="success"
            size="medium"
            @click="passUser()"
            >启用</el-button
          ></el-col
        >
        <el-col :span="2"
          ><el-button
            class="button-size"
            type="primary"
            size="medium"
            @click="showDialogQueryVisible = true"
            >高级筛选</el-button
          ></el-col
        >
        <el-col :span="2"
          ><el-button
            class="button-size"
            type="primary"
            size="medium"
            @click="downloadExcel"
            >导出</el-button
          ></el-col
        >
        <el-col :span="8" :offset="8">
          <el-input
            placeholder="输入手机号或昵称搜索"
            v-model="queryInfo.idOrPhone"
            clearable
            @clear="getUserList()"
            @click="queryUser()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="queryUser()"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <!-- <el-row :gutter="5">
        <el-col :span="2"
          ><el-input v-model="queryInfo.city" placeholder="地区"> </el-input
        ></el-col>
        <el-col :span="3"
          ><el-input v-model="queryInfo.age_start" placeholder="大于年龄">
          </el-input
        ></el-col>
        <el-col :span="3"
          ><el-input v-model="queryInfo.age_end" placeholder="小于年龄">
          </el-input
        ></el-col>
        <el-col :span="3"
          ><el-select v-model="queryInfo.sex" placeholder="性别">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option> </el-select
        ></el-col>
        <el-col :span="3"
          ><el-select v-model="queryInfo.role" placeholder="用户类型">
            <el-option label="普通用户" value="6"></el-option>
            <el-option label="VIP用户" value="7"></el-option> </el-select
        ></el-col>
      </el-row>

      <el-row :gutter="10" style="margin-top: 5px">
        <el-col :span="7">
          <el-date-picker
            v-model="timeRange.register"
            type="daterange"
            range-separator="至"
            start-placeholder="注册起始"
            end-placeholder="注册截至"
            value-format="yyyy-MM-dd"
          >
            >
          </el-date-picker>
        </el-col>
        <el-col :span="7">
          <el-date-picker
            v-model="timeRange.login"
            type="daterange"
            range-separator="至"
            start-placeholder="登录起始"
            end-placeholder="登录截至"
            value-format="yyyy-MM-dd"
          >
            >
          </el-date-picker>
        </el-col>

        <el-col :span="1">
          <el-button type="primary" @click="search()" icon="el-icon-search"
            >综合搜索</el-button
          >
        </el-col>
      </el-row> -->

      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe @selection-change="changeFun">
        <el-table-column type="selection" width="55" prod="id">
        </el-table-column>
        <el-table-column label="ID" prop="id" sortable></el-table-column>
        <el-table-column label="昵称" prop="nickName"></el-table-column>
        <el-table-column label="手机号" prop="account"></el-table-column>
        <el-table-column label="性别" prop="sex">
          <template slot-scope="scope">
            <div v-if="scope.row.sex === 0">男</div>
            <div v-if="scope.row.sex === 1">女</div>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" prop="lastLoginTime">
          <template slot-scope="scope">
            {{ scope.row.lastLoginTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="用户等级" prop="rank">
          <!-- <template slot-scope="scope">
            {{ scope.row.role | getRoleName(authList) }}
          </template> -->
          <template slot-scope="scope">
            {{ scope.row.role | rankText() }}
          </template>
        </el-table-column>
        <el-table-column label="所在城市" prop="city"> </el-table-column>
        <!-- 状态 冻结 正常-->
        <el-table-column label="状态" sortable>
          <template slot-scope="scope">
            <div v-if="scope.row.status === 1">
              <p><b style="color: blue; font-size: 15px">·</b> 正常</p>
            </div>
            <div v-if="scope.row.status === 0">
              <p><b style="color: red; font-size: 15px">·</b> 禁用</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="danger"
              size="mini"
              @click="userStateChanged(scope.row)"
              >禁用</el-button
            >
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              size="mini"
              @click="userStateChanged(scope.row)"
              >启用</el-button
            >
            <el-button type="primary" size="mini" @click="see(scope.row.id)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 展示单个用户信息框 -->
    <el-dialog title="用户信息" :visible.sync="showDialogVisible" width="50%">
      <div>
        <label for="nickName">昵称:</label>
        <p id="nickName">{{ this.nowUserInfo.nickName }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="sex">性别:</label>
        <p id="sex">{{ this.nowUserInfo.sex | sexFormat }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="city">城市:</label>
        <p id="city">{{ this.nowUserInfo.city }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="phone">手机:</label>
        <p id="phone">{{ this.nowUserInfo.phone }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="birthday">生日:</label>
        <p id="birthday">{{ this.nowUserInfo.birthday | dateFormatNoTime }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="profile">自我介绍:</label>
        <p id="profile">{{ this.nowUserInfo.profile }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="rank">等级:</label>
        <p id="rank">{{ this.nowUserInfo.rank }}</p>
      </div>
      <el-divider></el-divider>
      <div>
        <label for="driveAge">驾龄:</label>
        <p id="driveAge">{{ this.nowUserInfo.driveAge }}</p>
      </div>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 高级筛选弹出框 -->
    <el-dialog
      title="高级筛选"
      :visible.sync="showDialogQueryVisible"
      width="50%"
    >
      <el-form
        :label-position="labelPosition"
        label-width="80px"
        :model="formLabelAlign"
      >
        <el-form-item label="性别">
          <el-radio-group v-model="queryInfo.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader
            clearable
            :options="cityData"
            v-model="cityArray"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input
            class="button-size"
            v-model="queryInfo.age_start"
            placeholder="大于年龄"
          ></el-input>
          ——
          <el-input
            class="button-size"
            v-model="queryInfo.age_end"
            placeholder="小于年龄"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="timeRange.register"
            type="daterange"
            range-separator="至"
            start-placeholder="注册起始"
            end-placeholder="注册截至"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="登陆时间">
          <el-date-picker
            v-model="timeRange.login"
            type="daterange"
            range-separator="至"
            start-placeholder="登录起始"
            end-placeholder="登录截至"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="用户等级">
          <el-select
            v-model="queryInfo.rank"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in rankList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="search()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import cityData from './citydata.js'
import rankList from './rankdata.js'

export default {
  data() {
    return {
      // 查询条件
      queryInfo: {
        idOrPhone: '',
        currentPage: 1,
        pageSize: 10,
        city: null,
        age_start: null,
        age_end: null,
        sex: null,
        role: null,
        rank: null,
        create_time_start: null,
        create_time_end: null,
        login_time_start: null,
        login_time_end: null,
      },
      // 时间起始
      timeRange: {
        register: null,
        login: null,
      },
      // 城市数组
      cityArray: [],
      // 用户列表
      userList: [],
      // 总的数据条数
      total: 0,
      // 用户信息展示框
      showDialogVisible: false,
      // 当前用户的具体信息
      nowUserInfo: {},
      // 角色列表
      authList: [],
      // 筛选用户条件弹窗
      showDialogQueryVisible: false,
      // Form对齐
      labelPosition: 'left',
      formLabelAlign: {
        name: '',
        region: '',
        type: '',
      },
      // 地区数据
      cityData,
      // 等级数据
      rankList,
      // 表格选中的ID列表
      multipleSelection: [],
      // 生成excel
      excelData: [],
    }
  },
  created() {
    // 加载页面时 加载一次数据
    this.getUserList()
    this.getAuth()
  },
  methods: {
    // 分页获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users/query/user/wrapper', {
        params: this.queryInfo,
      })
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.userList = []
      this.userList = res.data.data
      this.total = res.data.total
      console.log(res.data.data)
      // const { data: res } = await this.$http.get('users/query/user/page', {
      //   params: this.queryInfo,
      // })
      // if (res.code !== 200) return this.$message.error('Error:' + res.message)
      // this.userList = res.data.data
      // this.total = res.data.total
      // console.log(res)
    },
    // 表格 分页单页数目切换
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      console.log('pagesize' + this.queryInfo.pageSize)
      this.getUserList()
    },
    // 表格 分页页数切换
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getUserList()
    },
    // 显示用户具体信息
    async showUserInfo(id) {
      const { data: res } = await this.$http.get('users/query/info/id/' + id)
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.showDialogVisible = true
      this.nowUserInfo = res.data

      console.log(res.data)
    },
    // 根据id或者phone 搜索用户信息
    async queryUser() {
      const { data: res } = await this.$http.get(
        '/users/query/user/id/' + this.queryInfo.idOrPhone
      )
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.userList = []
      if (res.data.data !== null) {
        this.userList.push(res.data.data)
        this.total = res.data.total
        console.log(res.data.data)
      }
      if (res.data.data === null) {
        const { data: res } = await this.$http.get(
          '/users/query/user/phone/' + this.queryInfo.idOrPhone
        )
        if (res.code !== 200) return this.$message.error('Error:' + res.message)
        this.userList = []
        if (res.data.data !== null) {
          this.userList.push(res.data.data)
          this.total = res.data.total
          console.log(res.data.data)
        }
      }
    },
    // 复合搜索
    async search() {
      // 关闭弹出框
      this.showDialogQueryVisible = false

      // 数据预处理
      this.city = null
      this.queryInfo.login_time_start = null
      this.queryInfo.login_time_end = null
      this.queryInfo.create_time_start = null
      this.queryInfo.create_time_end = null
      if (this.timeRange.login !== null) {
        this.queryInfo.login_time_start = this.timeRange.login[0]
        this.queryInfo.login_time_end = this.timeRange.login[1]
      }
      if (this.timeRange.register !== null) {
        this.queryInfo.create_time_start = this.timeRange.register[0]
        this.queryInfo.create_time_end = this.timeRange.register[1]
      }
      if (this.cityArray !== null) {
        this.queryInfo.city = this.cityArray.join('/')
      }
      console.log(this.queryInfo)
      // todo

      const { data: res } = await this.$http.get('users/query/user/wrapper', {
        params: this.queryInfo,
      })
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.userList = []
      this.userList = res.data.data
      this.total = res.data.total
      console.log(res.data.data)
    },
    // 解冻 解冻用户账户
    async userStateChanged(row) {
      // 冻结
      if (row.status === 1) {
        const { data: res } = await this.$http.get('users/frozen/' + row.id)
        if (res.code !== 200) return this.$message.error('Error:' + res.message)
        // 同步更新数据
        row.status = 0
        return this.$message.success('禁用用户成功')
      }
      // 解冻
      if (row.status === 0) {
        const { data: res } = await this.$http.get('users/thaw/' + row.id)
        if (res.code !== 200) return this.$message.error('Error:' + res.message)
        // 同步更新数据
        row.status = 1
        return this.$message.success('启用用户成功')
      }
    },
    // 删除用户
    async deleteUser(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.$message.success('删除用户成功')
      // 重新加载一次
      this.getUserList()
    },
    // 获取设置的角色
    async getAuth() {
      const { data: res } = await this.$http.get('admin/role')
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.authList = res.data
      console.log(this.authList)
    },
    // 表格选中
    changeFun(val) {
      this.multipleSelection = val
    },
    // 导出数据
    excel() {
      console.log(this.multipleSelection)
    },
    // 批量禁用 多条用户数据
    async bpUser() {
      // 提示数据
      let s = ''
      let success = 0
      let wrong = 0
      for (var i = 0; i < this.multipleSelection.length; i++) {
        //如果是正常状态 进行冻结
        if (this.multipleSelection[i].status === 1) {
          const { data: res } = await this.$http.get(
            'users/frozen/' + this.multipleSelection[i].id
          )
          if (res.code !== 200) wrong += 1
          // 同步更新数据
          this.multipleSelection[i].status = 0
          success += 1
        }
      }
      return this.$message.info(
        '请求成功' + success + '条数据,' + '请求失败' + wrong + '条数据'
      )
    },
    // 批量启用 多条用户数据
    async passUser() {
      // 提示数据
      let s = ''
      let success = 0
      let wrong = 0
      for (var i = 0; i < this.multipleSelection.length; i++) {
        //如果是禁用状态 进行解冻
        if (this.multipleSelection[i].status === 0) {
          const { data: res } = await this.$http.get(
            'users/thaw/' + this.multipleSelection[i].id
          )
          if (res.code !== 200) wrong += 1
          // 同步更新数据
          this.multipleSelection[i].status = 1
          success += 1
        }
      }
      return this.$message.info(
        '请求成功' + success + '条数据,' + '请求失败' + wrong + '条数据'
      )
    },
    // 列表选中数据下载
    downloadExcel() {
      this.$confirm('确定下载选中数据的列表文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.excelData = this.multipleSelection // multipleSelection是一个数组，存储表格中选择的行的数据。
          this.export2Excel()
        })
        .catch(() => {})
    },
    // 数据写入excel
    export2Excel() {
      var that = this
      // console.log('list' + this.multipleSelection)
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/export2Excel') // 这里必须使用绝对路径，使用@/+存放export2Excel的路径
        const tHeader = [
          'ID',
          '昵称',
          '手机号',
          '性别',
          '注册时间',
          '最后登录时间',
          '用户等级',
          '所在城市',
          '状态',
        ] // 导出的表头名信息
        const filterVal = [
          'id',
          'nickName',
          'account',
          'sex',
          'createTime',
          'lastLoginTime',
          'rank',
          'city',
          'status',
        ] // 导出的表头字段名，需要导出表格字段名
        const list = that.excelDataFormat(that.excelData)
        // console.log('excel:' + list)
        const data = that.formatJson(filterVal, list)
        // console.log('excel:' + list)

        export_json_to_excel(tHeader, data, that.getExcelName()) // 导出的表格名称，根据需要自己命名
      })
    },
    // 格式转换，直接复制即可
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    },
    // 导出excel数据预处理
    excelDataFormat() {
      let list = this.excelData
      for (var i = 0; i < list.length; i++) {
        list[i].createTime = this.timeChange(list[i].createTime)
        list[i].lastLoginTime = this.timeChange(list[i].lastLoginTime)
        list[i].sex = this.sexChange(list[i].sex)
        list[i].status = this.statusChange(list[i].status)
      }
      return list
    },
    // excel文档名生成 取时间
    getExcelName() {
      let dt = new Date()
      return dt.toLocaleString()
    },
    // 时间格式转化
    timeChange(originVal) {
      const dt = new Date(originVal)
      const y = dt.getFullYear()
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      const d = (dt.getDate() + '').padStart(2, '0')

      const hh = (dt.getHours() + '').padStart(2, '0')
      const mm = (dt.getMinutes() + '').padStart(2, '0')
      const ss = (dt.getSeconds() + '').padStart(2, '0')
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    },
    // 性别格式转化
    sexChange(sex) {
      if (sex === 1) {
        return '女'
      } else if (sex == 0) {
        return '男'
      }
    },
    // 状态格式转化
    statusChange(status) {
      if (status === 1) {
        return '正常'
      } else if (status === 0) {
        return '禁用'
      }
    },
    // 查看按钮跳转
    see(userId) {
      this.$router.push({
        path: 'userinfo',
        query: {
          name: 'id',
          code: userId,
        },
      })
    },
  },
  filters: {
    rankText: function (value) {
      if (!value) return ''
      return 'VIP' + value
    },
    getRoleName: function (value, auth) {
      if (!value) return ''
      for (let i = 0, len = auth.length; i < len; i++) {
        if (value == auth[i].id) {
          return auth[i].name
        }
      }
    },
    getCity: function (value) {
      if (!value) return ''
      let array = new Array()
      array = (value + '').split('/')
      if (array != null) {
        if (array.length >= 2) {
          return array[1]
        } else if (array.length == 1) {
          return array[0]
        }
      }
      return array
    },
  },
}
</script>

<style lang="less" scope>
.button-size {
  width: 90px;
}
</style>
